import { Button, InputItem, List, Radio, TextareaItem, Toast, WhiteSpace, WingBlank } from "antd-mobile";
import { addon } from "pao-aop";
import { BaseReactElement, BaseReactElementControl, BaseReactElementState, reactControl } from "pao-aop-client";
import React from "react";
import { getUuid, request, setMainFormTitle } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { IntelligentElderlyCareAppStorage } from "src/projects/app/appStorage";
import { encodeUrlParam, PAGE_TYPE, ROUTE_PATH } from "src/projects/app/util-tool";
import { SocietyInformation } from "../society-information";
const RadioItem = Radio.RadioItem;
/**
 * 组件：慈善捐款状态
 */
export interface CharitableDonateViewState extends BaseReactElementState {
    // 捐款项目
    donate_project_id?: string;
    // 捐款人名义
    donate_name?: string;
    // 捐款金额
    donate_money?: number;
    // 联系方式
    contacts?: string;
    // 是否匿名
    is_anonymous?: string;
    // 捐款意向
    donate_intention?: string;
    // 捐款留言
    remark?: string;
    // 防止重复发送
    isSend?: boolean;
    // 项目列表
    project_list?: any;
    project_show_value?: any;
    // 慈善会信息
    society_info?: any;
}

/**
 * 组件：慈善捐款
 * 慈善捐款
 */
export class CharitableDonateView extends BaseReactElement<CharitableDonateViewControl, CharitableDonateViewState> {

    constructor(props: any) {
        super(props);
        this.state = {
            donate_name: '',
            donate_money: 0,
            contacts: '',
            is_anonymous: '否',
            remark: '',
            donate_intention: '',
            isSend: false,
            project_list: [],
            society_info: [],
        };
    }
    componentDidMount() {
        let user = IntelligentElderlyCareAppStorage.getCurrentUser();
        if (!user) {
            this.props.history!.push(ROUTE_PATH.login);
            return;
        }
        // 获取慈善会信息
        request(this, AppServiceUtility.charitable_service.get_charitable_society_list!({}, 1, 1))
            .then((data: any) => {
                if (data.result && data.result[0]) {
                    this.setState({
                        society_info: data.result[0] || [],
                    });
                }
            })
            .catch(error => {
                Toast.fail(error.message);
            });
        if (this.props.match!.params.key) {
            this.setState({
                donate_project_id: this.props.match!.params.key,
                project_show_value: [this.props.match!.params.key],
            });
        }
    }
    changeValue = (e: any, inputName: any) => {
        this.setState({
            [inputName]: e
        });
    }
    goDonate = (): boolean => {
        // if (!this.state.donate_project_id) {
        //     Toast.fail('请选择捐款项目', 1);
        //     return false;
        // }
        let { donate_name, donate_money, is_anonymous, donate_intention, contacts, remark } = this.state;
        if (!donate_name) {
            Toast.fail('请输入申请人/企业', 1);
            return false;
        }
        if (!donate_money) {
            Toast.fail('请输入捐款金额', 1);
            return false;
        }
        if (isNaN(Number(this.state.donate_money))) {
            Toast.fail('请输入正确的捐款金额', 1);
            return false;
        }
        if (Number(donate_money) < 0.1) {
            Toast.fail('捐款金额必须大于￥0.1', 1);
            return false;
        }
        if (!donate_intention) {
            Toast.fail('请输入捐款意向', 1);
            return false;
        }
        if (!contacts) {
            Toast.fail('请输入联系方式', 1);
            return false;
        }
        if (!is_anonymous) {
            Toast.fail('请选择是否匿名', 1);
            return false;
        }
        if (!remark) {
            Toast.fail('请输入捐赠留言', 1);
            return false;
        }
        Toast.loading('Loading...', 3, () => {
            console.log('Load complete !!!');
        });

        const out_trade_no: string = getUuid();

        var param: any = {
            // donate_project_id: this.state.donate_project_id,
            donate_name: this.state.donate_name,
            donate_money: Number(this.state.donate_money),
            donate_intention: donate_intention,
            remark: remark || '',
            contacts: contacts || '',
            is_anonymous: is_anonymous,
            out_trade_no: out_trade_no,
            // 个人捐赠标识
            donate_type: '个人',
        };
        Toast.loading('Loading...', 11, () => {
        });
        let st = setTimeout(
            () => {
                Toast.hide();
                Toast.fail('提交失败，请稍候再试', 3);
            },
            10000
        );
        request(this, AppServiceUtility.charitable_service.update_charitable_donate!(param))
            .then((datas: any) => {
                if (datas === 'Success') {
                    clearTimeout(st);
                    Toast.hide();

                    // 前往支付流程
                    let buy_param = JSON.stringify({
                        page_type: PAGE_TYPE.DONATION,
                        page_info: Number(this.state.donate_money),
                        abstract: '捐款',
                        remarks: "慈善捐款",
                        out_trade_no: out_trade_no,
                        product_desc: "慈善捐款",
                        // 附加信息（可选），微信异步通知会原样返回
                        attach: "donate"
                    });

                    this.props.history!.push(ROUTE_PATH.payment + '/' + encodeUrlParam(buy_param));

                } else {
                    Toast.fail('提交失败，请稍候再试', 3);
                }
            }).catch((error: Error) => {
                Toast.fail(error.message);
            });
        return false;
    }
    changeProject = (e: any) => {
        console.log(e);
        this.setState({
            donate_project_id: e[0],
            project_show_value: e,
        });
    }
    render() {
        setMainFormTitle("慈善捐款");
        // let project = this.state.project_list;
        // let project_list: any[] = [];
        // project!.map((item: any) => {
        //     project_list.push({
        //         label: item.project_name,
        //         value: item.id,
        //     });
        // });
        // const { getFieldProps } = this.props.form;
        // const
        //     borderBoth = {
        //         borderTop: '1px solid #ddd',
        //         borderBottom: '1px solid #ddd',
        //     };
        const is_anonymous_data = [
            { value: '否', label: '否' },
            { value: '是', label: '是' },
        ];
        const is_anonymous = this.state.is_anonymous;
        // const project_show_value = this.state.project_show_value;
        const society_info = this.state.society_info;
        return (
            <div>
                {/* <List renderHeader={() => '捐款项目'}>
                    <Picker data={project_list} cols={1} value={project_show_value} onChange={(e) => this.changeProject(e)}>
                        <List.Item arrow="horizontal" style={borderBoth}>捐款项目</List.Item>
                    </Picker>
                </List> */}
                <List renderHeader={() => '捐款人/企业'}>
                    <InputItem clear={true} placeholder="捐款人/企业" onChange={(e) => this.changeValue(e, 'donate_name')} />
                </List>
                <List renderHeader={() => '捐款金额'}>
                    <InputItem placeholder="请输入捐款金额" onChange={(e) => this.changeValue(e, 'donate_money')} />
                </List>
                <List renderHeader={() => '捐款意向'}>
                    <InputItem placeholder="请输入捐款意向" onChange={(e) => this.changeValue(e, 'donate_intention')} />
                </List>
                <List renderHeader={() => '联系方式'}>
                    <InputItem placeholder="请输入联系方式" onChange={(e) => this.changeValue(e, 'contacts')} />
                </List>
                <List renderHeader={() => '是否匿名'}>
                    {is_anonymous_data.map(i => (
                        <RadioItem key={i.value} checked={is_anonymous === i.value} onChange={() => this.changeValue(i.value, 'is_anonymous')}>
                            {i.label}
                        </RadioItem>
                    ))}
                </List>
                <List renderHeader={() => '捐赠留言'}>
                    <TextareaItem placeholder="请输入捐赠留言" rows={3} autoHeight={true} onChange={(e) => this.changeValue(e, 'remark')} />
                </List>
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
                <WingBlank size="lg">
                    <Button type="primary" onClick={this.goDonate}>前往捐赠</Button>
                </WingBlank>
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
                {society_info && society_info['id'] ? <SocietyInformation data_info={society_info} /> : null}
            </div>
        );
    }
}

/**
 * 控件：慈善捐款控制器
 * 慈善捐款
 */
@addon('CharitableDonateView', '慈善捐款', '慈善捐款')
@reactControl(CharitableDonateView, true)
export class CharitableDonateViewControl extends BaseReactElementControl {

}